<template>
  <div class="Material-right">
    <div class="title">
      <div class="title-left">
        图片素材 (共{{allImg}}条)
        <!--<p>删除后的文章或图片在回收站会永久保存，彻底删除请手动动操作</p>-->
        <p>在写文章或设置封面时，都需要上传图片素材</p>
      </div>
    </div>

    <!--liuyiding add tag新的 -->
    <div class="edit-column">
      <span>图片类别：</span>
      <div class="tag-list revise-tool clearfix">
        <div class="tag-list_tab" :class="{selector:tabIndex == 0}" @click="clickTab(0)">{{listFolderAll[0].categoryName}}({{allImg}})</div>
        <div v-show="listFolderAll[1]" class="tag-list_tab" :class="{selector:tabIndex == 1}" @click="clickTab(1)">
          {{listFolderAll[1] ? listFolderAll[1].categoryName : '默认分类'}}({{listFolderAll[1] ? listFolderAll[1].count : 0}})
        </div>
        <!--tag-->
        <div class="revise-tool-input" :class="{selector:tabIndex == index+2}"
             v-for="(item,index) in listFolderAll.slice(2)">
          <svg class="icon" :class="{iconEdit:iconWriteNum == index}" ref="iconWrite" aria-hidden="true"
               @click="showEdit(index+2)">
            <use xlink:href="#icon-edit"></use>
          </svg>
          <input v-show="item.show" ref="focusC" v-model="item.categoryName" type="text" @blur="editFolder(index+2)"/>
          <span v-show="!item.show" ref="nameSpan"
                @click="clickTab(index + 2)"
                :title="item.categoryName"><em>{{item.categoryName}}</em>({{item.count}})</span>
        </div>
        <div class="revise-tool-input" v-show="showFile"><input type="text" ref="inputName" v-model="fileName"
                                                                placeholder="新建文件夹" @blur="createFolder"></div>
        <div @click="addFile" class="tag-list_add">
          <i></i>
        </div>
      </div>
    </div>
    <!--图片列表-->
    <div class="img-list" v-loading="loading">
      <ul class="clearfix">

        <li class="upload-img" v-show="pageNow == 1">
          <el-upload action="upload/image?type=2"
                     ref="upload"
                     :before-upload="beforeAvatarUpload"
                     :http-request='submitUpload'
                     :on-change="uploadOnChange"
                     :show-file-list="false">
            <el-button>
              <img src="../../assets/images/icon-img.png" class="icon-img"/>
              <p>上传图片</p>
            </el-button>
          </el-upload>
        </li>


        <li class="upload-li img-list-li" v-if="!pass && progress !== 0">
          <el-progress type="line" :percentage="progress" :status="proStatus"></el-progress>
          <p>正在上传</p>
        </li>
        <li v-for="(item,index) in imgList" class="img-list-li" :class="{isBlock:index === imgListNum}">
          <div class="img-box">
            <img :src="item.url+'?x-oss-process=image/resize,m_fixed,h_100,w_160'"/>
          </div>

          <input type="text" ref='listFocus' v-show="item.show" v-model="item.materialName"
                 @blur="handleCancleClick(index)"/>
          <span v-show="!item.show" :class="{newName:index === isselect}">{{item.materialName}} </span>

          <div class="layer">

            <div class="del-img" @click="delImg(item.materialId,index)">
              <svg class="icon" aria-hidden="true">
                <use xlink:href="#icon-trash"></use>
              </svg>
            </div>
            <div class="new-name" @click="handleNewnameClick(index)">
              <svg class="icon" aria-hidden="true">
                <use xlink:href="#icon-edit-"></use>
              </svg>
            </div>
          </div>
        </li>

      </ul>
      <!--分页-->
      <div class="self-pagination" v-show="imgList.length">
        <pagination @currentChange="handleCurrentChange" :currentPg="pageNow" :pageSize="pSize"
                    :total="allPage"></pagination>
      </div>

      <!--刘一丁新增 无内容提示-->

      <div class="nocontent-tips" v-show="listIsNull">
        <img src="../../assets/images/no-pic.png"/>
        <p>啧啧，您还未上传任何图片！</p>
      </div>
    </div>

  </div>
</template>

<script>
  import pagination from '../common/pagination.vue'
  import util from '../../lib/util'
  import {SUCCESS_CODE} from '../../lib/returnCode'

  export default {
    name: 'MaterialRight',
    components: {
      pagination
    },
    data() {
      return {
        isselect: '',
        imgListNum: '', //控制样式
        iconWriteNum: '-1', //更改标签名点击之后icon的隐藏
        showList: false,
        showRevise: false,
        fileList: [],

        /*最新变量*/
        listFolderAll: [{
          categoryId: 0,
          categoryName: "全部分类",
          count: 0
        }],
        //新建文件夹名字
        fileName: '',
        /*图片list*/
        imgList: [],
        showFile: false,
        /*图片url*/
        imgUrl: [],
        tabIndex: 0,
        allPage: 1,
        allImg: 0,
        pageNow: 1,
        pSize: 30,

        loading: false,
        listIsNull: false,
        /*上传图片List*/
        uploadImgList: [],
        progress: 0,//上传进度
        pass: null,//是否上传成功,

      }
    },
    created() {

      this.ajaxUserList();

    },
    computed: {
      proStatus() {//上传状态
        if (this.pass) {
          return 'success'
        } else if (this.pass == false) {
          return 'exception'
        } else {
          return ''
        }
      }
    },
    methods: {

      // 编辑文件名
      showEdit: function (index) {
        let nameSpanWidth = this.$refs.nameSpan[index - 2].clientWidth;

        let data = this.listFolderAll;
        data[index].show = true;
        this.listFolderAll = data;
        //更改标签名点击之后icon的隐藏
        this.iconWriteNum = index - 2;
        /*获取焦点   动态修改input宽度*/
        this.$nextTick(() => {
          this.$refs.focusC[index - 2].focus();

          this.$refs.focusC[index - 2].style.width = nameSpanWidth - 40 + "px";

        });

      },

      // 请求素材列表
      ajaxUserList: function () {

        util.ajax.post('category/list', {
          isDel: 0
        }).then((res) => {

          if (res.data) {

            let data = res.data ? res.data.list.map((item) => {

              item.show = false;

              return item;

            }) : [];

            this.listFolderAll[0].count = res.data.totalCount;
            this.allImg = res.data.totalCount;

            this.listFolderAll = this.listFolderAll.concat(data);

            // 获取文件夹列表
            this.folderList = JSON.parse(JSON.stringify(data));

            this.clickTab(0);
          } else {

            this.$message.error(res.msg);
          }

        })

      },
      //创建文件夹
      createFolder: function () {

        if (!this.fileName.length) {

          this.$message.error('文件夹不可以为空');

        }

        util.ajax.post('category/insert', {
          categoryName: this.fileName
        }).then((res) => {



          if (res.code == SUCCESS_CODE) {

            if (res.data) {
              this.fileName = '';

              //this.ajaxUserList();

              this.showFile = false;

              //this.ajaxUserList();
              this.listFolderAll.push({
                "categoryId": res.data.categoryId,
                "categoryName": res.data.categoryName,
                "show": false,
                "count": 0
              });

              this.folderList.push({
                "categoryId": res.data.categoryId,
                "categoryName": res.data.categoryName,
                "show": false,
                "count": 0
              })
            }
          } else {

            this.$message.error(res.msg);
            setTimeout(() => {
              this.showFile = false;
            }, 1000)

          }

        });
      },
      // 点击分类
      clickTab: function (index) {

        this.tabIndex = index;

        let params = {
          categoryId: this.listFolderAll[index].categoryId,
          pageNo: 1,
          pageSize: this.pSize
        };
        this.pageNow = 1;

        //loading
        this.loading = true;
        // tab切换不显示默认图片
        this.listIsNull = false;
        this.ajaxList(params);

      },
      ajaxList: function (params) {
        util.ajax.post('material/list', {
          ...params
        }).then((res) => {

          if (res.data) {

            if (!res.data.list.length) {
              this.listIsNull = true;
            }

            this.allPage = res.data.total;

            let data = res.data.list.map((item) => {

              item.show = false;

              return item;

            });

            this.loading = false;

            this.imgList = data;

            this.allData = JSON.parse(JSON.stringify(data));
          }

        })
      },
      // input 获取焦点
      addFile: function () {

        this.showFile = !this.showFile;

        setTimeout(() => {
          this.$refs.inputName.focus();
        }, 500)

      },

      //删除图片
      delImg: function (id, index) {

        util.ajax.post('material/del', {
          id
        }).then((res) => {

          if (res.code == SUCCESS_CODE) {

            let categoryId = this.imgList[index].categoryId;

            this.listFolderAll[this.tabIndex].count = this.listFolderAll[this.tabIndex].count - 1;

            if (this.tabIndex === 0) {
              let folderIndex = 0;

              this.listFolderAll.filter((item, index) => {

                if (item.categoryId == categoryId) {

                  folderIndex = index;
                  return item;
                }
              });

              this.listFolderAll[folderIndex].count = this.listFolderAll[folderIndex].count - 1;

            }

            // 图片素材总数
            this.allImg = this.allImg - 1;

            //更新列表
            let params = {
              categoryId: this.listFolderAll[this.tabIndex].categoryId,
              pageNo: this.pageNow,
              pageSize: this.pSize
            };

            if (index == 0 && this.imgList.length <= 1 && this.pageNow >= 2) {
              this.pageNow = this.pageNow - 1;
              params.pageNo = this.pageNow;
            }

            this.ajaxList(params);

          } else {

            this.$message.error(res.msg);
          }

        })

      },

      // 修改图片素材名
      handleCancleClick(index) {

        this.isselect = '';
        this.imgListNum = '';

        let item = this.imgList[index];
        let itemC = this.allData[index];





        if (!item.materialName) {

          this.imgList[index].materialName = itemC.materialName;
          this.$message.error('图片名称不可以为空');
          this.imgList[index].show = false;

          return
        }

        if (item.materialName == itemC.materialName) {
          this.imgList[index].show = false;
          return
        }

        let params = {

          "materialId": item.materialId,

          "categoryId": item.categoryId,

          "materialName": item.materialName,

          "materialUrl": item.materialUrl,

          "materialType": item.materialType,

          "isDel": 0

        };



        util.ajax.post('material/update', {
          ...params
        }).then((res) => {

          // todu

          if (res.code != SUCCESS_CODE) {

            this.$message.error(res.msg);
          }

          this.imgList[index].show = false;
        })

      },
      // 修改文件夹名字
      editFolder: function (index) {
        //更改标签名点击之后icon的隐藏
        this.iconWriteNum = -1;
        let data = this.listFolderAll[index];

        let params = {
          categoryId: data.categoryId,
          categoryName: data.categoryName
        };


        //文件夹名字为空
        if (!data.categoryName) {

          this.listFolderAll[index].categoryName = this.folderList[index - 1].categoryName;
          this.listFolderAll[index].show = false;

          return

        }

        //名称没有修改
        if (data.categoryName == this.folderList[index - 1].categoryName) {

          this.listFolderAll[index].show = false;

          return
        }
        util.ajax.post('category/update', {
          ...params
        }).then((res) => {

          let chooseName = this.listFolderAll;

          if (res.code == SUCCESS_CODE) {

            chooseName[index].show = false;

            this.listFolderAll = chooseName;

          } else if (res.code == '1014') {



            chooseName[index].categoryName = this.folderList[index - 1].categoryName;

            this.$message.error(res.msg);

          } else {

            this.$message.error(res.msg);
          }

          this.listFolderAll[index].show = false;
        })

      },

      // 点击重命名
      handleNewnameClick(index) {

        this.isselect = index;
        this.imgListNum = index;

        this.imgList[index].show = true;

        this.$nextTick(() => {
          this.$refs.listFocus[index].focus();

        });

      },
      // 文件状态改变时的钩子
      uploadOnChange: function (file, fileList) {



        if (file.status == 'ready') {



          //重置progress组件
          this.pass = null;
          this.progress = 0;

        } else if (file.status == 'fail') {

          this.$message.error('图片上传出错，请刷新重试!');
        }

      },
      //上传文件之前的钩子
      beforeAvatarUpload: function (file) {

        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 1;

        if (!isJPG) {

          this.$message.error('上传图片只能是 JPG,PNG 格式!');

        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 1MB!');

        }
        return isJPG && isLt2M;

      },
      //上传图片
      submitUpload: function (content) {

        let fd = new FormData();

        fd.append('fileData', content.file);

        util.ajax.postUpload('upload/image?type=2', fd, (progressEvent) => {
          var complete = (progressEvent.loaded / progressEvent.total * 100 | 0);
          this.progress = complete;
        }).then((res) => {


          if (res.code != SUCCESS_CODE) {
            this.$message.error(res.msg);
            this.pass = false;
            return
          }
          if (res.data) {
            // 没有价值图片显示为空
            this.listIsNull = false;

            let category = this.listFolderAll[this.tabIndex];

            // 对应数据文件夹数目+1
            this.listFolderAll[this.tabIndex].count = this.listFolderAll[this.tabIndex].count + 1;
            if (this.tabIndex == 0) {
              this.listFolderAll[1].count = this.listFolderAll[1].count + 1;
            }

            let params = {
              "categoryId": category.categoryId,
              "materialName": res.data.originalFileName,
              "materialUrl": res.data.key,
              "materialType": 1
            };

            util.ajax.post('material/insert', {
              ...params
            }).then(() => {

              // 上传图片成功
              this.pass = true;
              this.allImg = this.allImg + 1;
              this.handleCurrentChange(this.pageNow);
            });

          } else {
            this.pass = false;
          }

        });
        return false
      },

      handleCurrentChange: function (page) {



        this.pageNow = page;

        this.loading = true;
        let params = {
          categoryId: this.listFolderAll[this.tabIndex].categoryId,
          pageNo: page,
          pageSize: this.pSize
        };

        this.ajaxList(params);

      },

    }
  }
</script>

<style lang="scss" scoped>
  @import "@/assets/css/style.scss";
  @import "@/assets/css/style.scss";

  .Material-right {
    position: absolute;
    top: 83px;
    left: 220px;
    right: 0px;
    bottom: 0px;
    padding: 0px 20px;
    overflow-y: auto;
    .title {
      padding: 15px 0px;
      overflow: hidden;
      .title-left {
        float: left;
        font-size: $fs24;
        color: $listTitleColor;
        p {
          margin-top: 5px;
          font-size: $fs14;
          line-height: 20px;
          color: $vfConcentColor;
        }
      }
    }
    .upload-img {
      float: left;
      margin: 0px 20px 10px 0px;
      .el-button {
        padding: 0px !important;
        width: 160px;
        height: 140px;
        text-align: center;
        font-size: $fs14;
        border: 1px solid $listborderColor !important;
        background: $colorWhite !important;
        border-radius: 0px !important;
        color: $listTitleColor !important;
        span {
          display: inline-block;
          width: 160px;
          height: 140px;
          background: red;
        }
        &:hover {
          background: $borderbottomColor !important;
        }
        .icon-img {
          margin: 0px 0px 8px;
          width: 48px;
          height: 48px;
          color: $listborderColor;
        }
        p {
          font-size: $fs14;
          line-height: 20px;
          color: $listTitleColor;
        }
      }
    }
    .edit-column {
      display: flex;
      justify-content: flex-start;
      span {
        line-height: 28px;
        font-size: $fs14;
      }
      .tag-list {
        width: auto;
        max-width: 85%;
        .tag-list_tab {
          float: left;
          margin: 0px 10px 10px 0px;
          padding: 0px 15px;
          line-height: 28px;
          color: $listTitleColor;
          font-size: $fs14;
          border: 1px solid $listborderColor;
          border-radius: 15px;
          cursor: pointer;
          &:hover {
          }
        }
        .tag-list_add {
          position: relative;
          float: left;
          margin-left: 10px;
          width: 28px;
          height: 28px;
          line-height: 28px;
          text-align: center;
          border-radius: 50%;
          border: 1px solid $listborderColor;
          cursor: pointer;
          i {
            /*position: relative;*/
            width: 10px;
            height: 10px;
            /*top: 50%;*/
            /*left: 50%;*/
            &:before {
              content: '';
              display: block;
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
              width: 11px;
              height: 1px;
              background: $listTitleColor;
            }
            &:after {
              content: '';
              display: block;
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
              width: 1px;
              height: 11px;
              background: $listTitleColor;
            }
          }
        }
      }
    }
    .img-list {
      padding: 20px 0px 80px;
      .isBlock {
        input {
          border: 1px solid $vfConcentColor;
        }
        &:hover {
          .layer {
            display: none !important;
          }
        }
      }
      .upload-li {
        padding: 50px 0px 0px !important;
        width: 160px;
        height: 88px;
        text-align: center;
        border: 1px solid $listborderColor !important;
        .el-progress {
          margin: 0 auto;
          width: 100px;
        }
        p {
          font-size: $fs12;
          color: $listTitleColor;
          text-align: center;
          line-height: 20px;
        }
      }
      .img-list-li {
        position: relative;
        margin: 0px 20px 10px 0px;
        padding-bottom: 5px;
        float: left;
        width: 160px;
        &:hover {
          .layer {
            display: block;
          }
        }
        span {
          width: 100%;
          display: block;
          text-align: center;
          height: 30px;
          overflow: hidden;
          line-height: 30px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .img-box {
          margin-bottom: 5px;
          width: 100%;
          height: 100px;
          border: 1px solid $borderbottomColor;
          box-sizing: border-box;
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }
        input {
          /*border: 1px solid $vfConcentColor;*/
          border: none;
          width: 100%;
          text-align: center;
          height: 30px;
        }
        .newName {
          background: $borderbottomColor;
          border: 1px solid #3C4B68;
        }
        .layer {
          display: none;
          position: absolute;
          top: 1px;
          left: 0px;
          right: 1px;
          z-index: 2;
          height: 20px;
          .del-img,
          .new-name {
            opacity: 0.3;
            background: #000000;
            line-height: 30px;
            text-align: center;
            float: right;
            width: 30px;
            height: 30px;
            cursor: pointer;
            .icon {
              font-size: $fs20;
              color: $colorWhite;
            }
          }
        }
      }
    }
    .upload-layer {
      position: fixed;
      top: 50%;
      left: 50%;
      margin-left: -135px;
      margin-top: -204px;
      width: 270px;
      z-index: 1000;
      text-align: center;
      p {
        margin-bottom: 60px;
        text-align: center;
        font-size: $fs20;
        line-height: 40px;
        color: $listTitleColor;
      }
      .el-progress-bar {
        .el-progress__text {
          display: none !important;
        }
      }
      .upload-input {
        padding: 0px 20px;
        margin-top: 30px;
        width: 230px;
        height: 40px;
        line-height: 40px;
        font-size: $fs14;
        color: $listTitleColor;
        border: 1px solid $listTitleColor;
        border-radius: 20px;
      }
    }
    .save-btn,
    .cancel-btn {
      .icon {
        color: $colorWhite;
      }
      margin: 30px auto 0px;
      width: 180px;
    }
  }

  .revise-tool {
    .revise-tool-input {
      position: relative;
      float: left;
      margin: 0px 10px 10px 0px;
      height: 30px;
      border: 1px solid $listborderColor;
      border-radius: 15px;
      background: $colorWhite;
      font-size: 14px;
      letter-spacing: .2px;
      cursor: pointer;
      .icon {
        position: absolute;
        display: none;
        top: 6px;
        right: 10px;
        cursor: pointer;
        color: $vfConcentColor;
      }
      input {
        float: left;
        height: 30px;
        padding: 0px 20px !important;
        overflow: hidden;
        text-align: center;
        text-overflow: ellipsis;
        white-space: nowrap;
        border: none;
        border-radius: 20px;
        font-size: 14px;
        letter-spacing: .2px;

      }
      span {
        padding: 0px 30px !important;
        display: inline-block;
        line-height: 30px;
        em {
          float: left;
          margin-right: 5px;
          display: inline-block;
          max-width: 100px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          font-style: normal!important;
        }
      }
      &:hover {
        background: $borderbottomColor;
        color: $mainborderColor;
        .icon {
          display: block;
        }
        .iconEdit {
          display: none;
        }
        input {
          background: $colorWhite;
        }
      }
    }
  }

  .selector {
    border: 1px solid $mainborderColor !important;
    background: $mainborderColor !important;
    color: $colorWhite !important;
  }
</style>
